package com.meteor.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meteor.user.entity.SysOrg;
import com.meteor.user.query.SysOrgQuery;
import com.meteor.user.query.SysRoleQuery;
import com.meteor.user.query.SysRoleUserQuery;
import lombok.AllArgsConstructor;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.TreeUtils;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.user.convert.SysOrgConvert;
import com.meteor.user.mapper.SysOrgMapper;
import com.meteor.user.mapper.SysUserMapper;
import com.meteor.user.entity.SysUser;
import com.meteor.user.service.SysOrgService;
import com.meteor.user.vo.SysOrgVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 机构管理
 *
 * @author lynn
 * @date 2024/1/03
 */
@Service
@AllArgsConstructor
public class SysOrgServiceImpl extends BaseServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService {
    private final SysUserMapper sysUserMapper;

    @Override
    public List<SysOrgVO> getList(SysOrgQuery query) {
        Map<String, Object> params = new HashMap<>();

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope1("t1", "id","sys_org"));
//        params.put("merchantId",query.getMerchantId());

        // 机构列表
        List<SysOrgVO> entityList = baseMapper.getList(params);

        return TreeUtils.build(entityList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysOrgVO vo) {

        SysOrg entity = SysOrgConvert.INSTANCE.convert(vo);

        /*if(!ObjectUtil.isEmpty(vo.getMerchantId())&&ObjectUtils.isEmpty(vo.getPid())) {
            List<SysOrg> sysOrgs = baseMapper.selectList(new QueryWrapper<SysOrg>().eq("merchant_id", vo.getMerchantId()));
            if (sysOrgs.size() > 0) {
                throw new ServerException("该商户已存在机构");
            }
        }*/


        if(!ObjectUtils.isEmpty(vo.getPid())){
            SysOrg parent = baseMapper.selectById(vo.getPid());
            if(parent.getLevel()+1>2){
                throw new ServerException("机构层级不能超过2级");
            }
            entity.setLevel(parent.getLevel() + 1);
//            entity.setMerchantId(parent.getMerchantId());
        }else{
            entity.setLevel(1);
        }

        baseMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysOrgVO vo) {
        SysOrg entity = SysOrgConvert.INSTANCE.convert(vo);

        // 上级机构不能为自身
        if (entity.getId().equals(entity.getPid())) {
            throw new ServerException("上级机构不能为自身");
        }

        // 上级机构不能为下级
        List<String> subOrgList = getSubOrgIdList(entity.getId());
        if (subOrgList.contains(entity.getPid())) {
            throw new ServerException("上级机构不能为下级");
        }

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        // 判断是否有子机构
        long orgCount = count(new QueryWrapper<SysOrg>().eq("pid", id));
        if (orgCount > 0) {
            throw new ServerException("请先删除子机构");
        }

        // 判断机构下面是否有用户
        long userCount = sysUserMapper.selectCount(new QueryWrapper<SysUser>().eq("org_id", id));
        if (userCount > 0) {
            throw new ServerException("机构下面有用户，不能删除");
        }

        // 删除
        removeById(id);
    }

    @Override
    public List<String> getSubOrgIdList(String id) {
        // 所有机构的id、pid列表
        List<SysOrg> orgList = baseMapper.getIdAndPidList();

        // 递归查询所有子机构ID列表
        List<String> subIdList = new ArrayList<>();
        getTree(id, orgList, subIdList);

        // 本机构也添加进去
        subIdList.add(id);

        return subIdList;
    }

    @Override
    public List<SysOrgVO> orgMerchant(String merchantId) {
        // 机构列表
        List<SysOrgVO> entityList = baseMapper.getOrgMerchant(merchantId);

        return TreeUtils.build(entityList);
    }

    @Override
    public List<SysOrgVO> getAllList(SysOrgQuery query) {
        return null;
    }

    @Override
    public Map<String, List<String>> getSubMapOrgIdList(String orgId,Integer value) {
        // 所有机构的id、pid列表
        List<SysOrg> orgList = baseMapper.getIdAndPidList();

        // 递归查询所有子机构ID列表
        List<String> subIdList = new ArrayList<>();
        getTree(orgId, orgList, subIdList);

        // 本机构也添加进去
        subIdList.add(orgId);

        Map<String,List<String>> subMap = new HashMap<>();

        subMap.put(value.toString(),subIdList);

        return subMap;

    }

    private void getTree(String id, List<SysOrg> orgList, List<String> subIdList) {
        for (SysOrg org : orgList) {
            if (ObjectUtil.equals(org.getPid(), id)) {
                getTree(org.getId(), orgList, subIdList);

                subIdList.add(org.getId());
            }
        }
    }

}
